package cn.tedu.csmallpassport.filter;

import cn.tedu.csmallpassport.security.LoginPrincipal;
import cn.tedu.csmallpassport.web.JsonResult;
import cn.tedu.csmallpassport.web.ServiceCode;
import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.AuthProvider;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>JWT过滤器</p>
 *
 * <p>此过滤器的主要作用</p>
 * <ul>
 *     <li>接收客户端提交的请求中的JWT</li>
 * </ul>
 */
@Slf4j
@Component
public class JwtAuthorizationFilter extends OncePerRequestFilter {

    @Value("${csmall.jwt.secret-key}")
    private String secretKey;
    public static final int JWT_MIN_LENGTH = 113;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        log.debug("JWT过滤器开始执行……");
        // 根据业内惯用的做法，客户端提交的请求中的JWT应该存放于请求头（Request Header）中的名为Authorization属性中
        String jwt = request.getHeader("Authorization");
        log.debug("客户端携带的JWT：{}", jwt);

        if (!StringUtils.hasText(jwt) || jwt.length() < JWT_MIN_LENGTH){
            filterChain.doFilter(request,response);
            return;
        }

        Claims body =  null;
        try {
            body = Jwts.parser().setSigningKey(secretKey).parseClaimsJws(jwt).getBody();
        } catch (MalformedJwtException e) {
            response.setContentType("application/json; charset=utf-8");
            PrintWriter writer = response.getWriter();
            JsonResult<Void> jsonResult = JsonResult.fail(ServiceCode.ERROR_JWT_MALFORMED, "非法访问！");
            String jsonString = JSON.toJSONString(jsonResult);
            writer.println(jsonString);
            writer.close();
            return;
        } catch (SignatureException e) {
            response.setContentType("application/json; charset=utf-8");
            PrintWriter writer = response.getWriter();
            JsonResult<Void> jsonResult = JsonResult.fail(ServiceCode.ERROR_JWT_SIGNATURE, "非法访问！");
            String jsonString = JSON.toJSONString(jsonResult);
            writer.println(jsonString);
            writer.close();
            return;
        } catch (ExpiredJwtException e) {
            response.setContentType("application/json; charset=utf-8");
            PrintWriter writer = response.getWriter();
            JsonResult<Void> jsonResult = JsonResult.fail(ServiceCode.ERROR_JWT_EXPIRED, "您的登录信息已过期，请重新登录！");
            String jsonString = JSON.toJSONString(jsonResult);
            writer.println(jsonString);
            writer.close();
            return;
        } catch (Throwable e) {
            response.setContentType("application/json; charset=utf-8");
            PrintWriter writer = response.getWriter();
            JsonResult<Void> jsonResult = JsonResult.fail(ServiceCode.ERROR_UNKNOWN, "服务器忙，请稍后再次尝试！（开发过程中，如果看到此提示，请检查控制台的信息，并补充处理异常的方法）");
            String jsonString = JSON.toJSONString(jsonResult);
            writer.println(jsonString);
            writer.close();
            return;
        }
        Long id = body.get("id",Long.class);
        String username = body.get("username",String.class);
        String authoritiesJsonString = body.get("authoritiesJsonString",String.class);
        log.debug("id : {} ,username : {} ",id,username);

        LoginPrincipal loginPrincipal = new LoginPrincipal();
        loginPrincipal.setId(id);
        loginPrincipal.setUsername(username);

        List<SimpleGrantedAuthority> authorities = JSON.parseArray(authoritiesJsonString, SimpleGrantedAuthority.class);
        log.debug("将JWT中的权限列表的JSON字符串解析为List<GrantedAuthority>类型，结果：{}", authorities);


        Object principal = loginPrincipal;
        Object credentials = null;
        Authentication authentication = new UsernamePasswordAuthenticationToken(principal,credentials,authorities);
        SecurityContext context = SecurityContextHolder.getContext();
        context.setAuthentication(authentication);
        // 放行
        filterChain.doFilter(request, response);
    }

}
